import { recordAdvertisingOpen, getExternalUrl } from 'api/index'
import { getGroupCuntomConsulte } from '@/api/group'
import { contentCenterApi } from '@/api/contentCener'
import { tokenManage } from 'utils/Cache'
import { getMyHome } from 'api/my'

const jump = {
    data() {
        return {
            advertisingShow: false
        }
    },
    methods: {
        async jumpPage(params, flag = false) {
            if (params.action) {
                if (flag == true) {
                    this.$toast({
                        message: '跳转中~~~~',
                        forbidClick: true,
                        duration: 50
                    })
                    this.getRecordAdvertisingOpen(this.advertisingId)
                }
                if (params.action.type == 'prodDetail') {
                    //去商品详情
                    this.$router.push({
                        path: `/goodsDetail`,
                        query: {
                            goodsInfoId: params.action.target
                        }
                    })
                    this.showFlag()
                } else if (params.action.type == 'prodGroup') {
                    //商品分组-  去搜索列表
                    this.$router.push({
                        path: `/search/prodGroupList`,
                        query: {
                            prodGroupId: params.action.target,
                            name: params.action.name
                        }
                    })
                    this.showFlag()
                } else if (params.action.type == 'prodList') {
                    this.$router.push({
                        path: `/searchList`,
                        query: {
                            categoryId: params.action.target,
                            source: params.action.subType,
                            grade: params.action.grade
                        }
                    })
                    this.showFlag()
                } else if (params.action.type == 'category') {
                    this.$router.push({
                        path: `/searchList`,
                        query: {
                            categoryId: params.action.target,
                            source: params.action.type,
                            grade: params.action.grade
                        }
                    })
                } else if (params.action.type == 'url') {
                    //自定义url
                    let url = params.action.target
                    if (url.indexOf('http') != -1 || url.indexOf('https') != -1) {
                        window.location.href = url
                    } else if (url == '#') {
                        this.$toast('该功能暂未上线, 敬请期待~')
                    } else {
                        let params = { path: url }
                        // TODO去供应商首页 暂时简单做 例supplierHome?id=1
                        if (url.indexOf('supplierHome') != -1) {
                            const num = url.indexOf('=')
                            const id = url.slice(num + 1) //截取id
                            params = {
                                name: 'supplierHome',
                                query: {
                                    id
                                }
                            }
                        }else if(url.indexOf('externalSupplier') != -1) {
							// console.log(tokenManage.getToken(), "tokenManage.getToken()")
							// window.location.href = url
							if(!tokenManage.getToken()) {
								this.goLogin()
								return
							} else {
								let appId = this.getUrlValue(url, 'appId')
								let redirectChannel = this.getUrlValue(url, 'redirectChannel')
								redirectChannel = !redirectChannel ? '' : redirectChannel
								let { result } = await getMyHome()
								let { userId } = result
								let isLogin = result.phone ? true : false
								if(!isLogin) { //判断是否已授权手机登录 (兼容微信浏览器)
									// this.bindPhone.showPopup = true
									// this.$router.replace({ path: '/login', query: { redirect: this.$route.fullPath } })
									this.$utils.goLoginPage(this)
									return
								}
								this.getExternalUrl(appId, userId, redirectChannel)
								return
							}
						}
                        this.$router.push(params)
                    }
                    this.showFlag()
                } else if (params.action.type == 'marketing') {
                    //营销活动
                    let target = params.action.target
                    let url = ''
                    if (target == 'fighGroup') {
                        url = '/pages/fight/fight'
                    } else if (target == 'JoinGroup') {
                        url = '/marketingModules/group/groupList'
                        this.$toast('该功能暂未上线, 敬请期待~')
                        return
                    } else if (target == 'presell') {
                        url = '/marketingModules/presell/presellList'
                        this.$toast('该功能暂未上线, 敬请期待~')
                        return
                    } else {
                        url = '/marketingModules/seckill/seckillList'
                        this.$toast('该功能暂未上线, 敬请期待~')
                        return
                    }

                    this.$router.push({
                        path: url
                    })
                    this.showFlag()
                } else if (params.action.type == 'method') {
                    // 常用功能
                    let target = params.action.target
                    let url = ''
                    if (target == 'home' || target == 'car' || target == 'class' || target == 'my') {
                        switch (target) {
                            case 'home':
                                url = '/index'
                                break
                            case 'car':
                                url = '/cart'
                                break
                            case 'class':
                                url = '/category'
                                break
                            case 'my':
                                url = '/my'
                                break
                        }

                        this.$router.replace({
                            path: url
                        })
                        this.showFlag()
                    } else {
                        switch (target) {
                            case 'coupon':
                                url = '/walletModules/recCenter/recCenter'
                                break
                            case 'myMsg':
                                url = '/message'
                                break
                            case 'keep':
                                url = '/collection'
                                break

                            // 会员储值
                            case 'memberRecharge':
                                url = '/balance'
                                break

                            // 分销
                            case 'distribution':
                                url = '/applyExtension'
                                break

                            // 内容中心
                            case 'contentCenter':
                                url = '/contentCenter'
                                const contentResult = await this.getConterCenterStatus()
                                if (!contentResult) url = '/'

                                break

                            // 团购咨询
                            case 'groupAdvisory':
                                url = '/groupBuy'
                                const result = await this.getGrounpByStatus()
                                if (!result) url = '/'
                                break
                        }

                        this.$router.push({
                            path: url
                        })
                        this.showFlag()
                    }
                } else if (params.action.type == 'page') {
                    this.$router.push({
                        path: '/webpage',
                        query: {
                            pageId: params.action.target,
                            title: params.action.name
                        }
                    })
                    this.showFlag()
                }
            }
        },
        //记录弹窗广告打开次数
        getRecordAdvertisingOpen(advertisingId) {
            recordAdvertisingOpen({
                advertisingId
            })
        },

        showFlag() {
            this.advertisingShow = false
        },

        // 团购咨询的状态
        getGrounpByStatus() {
            return getGroupCuntomConsulte()
                .then((res) => {
                    if (!res.success) {
                        this.$toast(res.msg)
                        return false
                    }
                    return true
                })
                .catch((err) => {
                })
        },

        // 内容中心的状态
        getConterCenterStatus() {
            return contentCenterApi
                .getSetting()
                .then((res) => {
                    if (!res.success) {
                        this.$toast(res.msg)
                        return false
                    }
                    return true
                })
                .catch((err) => {
                })
        },
		//获取跳转链接
		getExternalUrl(appId, userId, redirectChannel) {
			getExternalUrl({ appId, userId, redirectChannel })
			.then((res) => {
				if (!res.success) {
				    this.$toast(res.msg)
				    return false
				}
				location.href = res.data
			})
			.catch((err) => {
			})
		},
		//获取url参数
		getUrlValue(url, kValue) {
		    var reg = /([^?&=]+)=([^?&=]+)/g, obj = {}, str = url;
		    url.replace(reg, function () {
		        obj[arguments[1]] = arguments[2];
		    })
		    for (var keyName in obj) {
		        if (keyName == kValue) {
		            return obj[keyName];
		            // break;
		        }
		    }
		},
		/**
		 * 清除本地token和清空vuex中token对象
		 * 去往登录页面
		 */
		goLogin() {
		    //清除token
		    tokenManage.clearToken()
		    this.$router
		        .replace({
		            path: '/login',
		            query: {
		                redirect: this.$router.currentRoute.fullPath
		            }
		        })
		        .catch((err) => {
		        })
		},
    }
}

export default jump
